<script setup lang="ts">
  import { nextTick, ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import UpdateCustomerServiceForm from './UpdateCustomerServiceForm.vue'

  const props = defineProps<{
    modelValue: boolean
    orderId: string
    currentEmp: string
  }>()

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  const visible = ref(false)
  const updateCustomerServiceFormRef = ref<InstanceType<typeof UpdateCustomerServiceForm> | null>(
    null,
  )

  const onClose = () => {
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  const onConfirm = async () => {
    if (updateCustomerServiceFormRef.value) {
      const res = await updateCustomerServiceFormRef.value.submit(props.orderId)
      if (res) {
        ElMessage({
          message: res.message,
          type: res.success ? 'success' : 'error',
          plain: true,
          duration: 5000,
          showClose: true,
        })

        if (res.success) {
          onClose()
          emits('update')
        }
      }
    }
  }

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      nextTick(() => {
        if (updateCustomerServiceFormRef.value) {
          updateCustomerServiceFormRef.value.getCustomerServiceOptionsFn()
        }
      })
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <HDialog
    title="改派客服"
    v-model="visible"
    @close="onClose"
    :loading="updateCustomerServiceFormRef && updateCustomerServiceFormRef.submitLoading"
  >
    <UpdateCustomerServiceForm ref="updateCustomerServiceFormRef" :current-emp="props.currentEmp" />
    <template #footer>
      <HButton is-modal type="primary" @click="onConfirm">确定</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </HDialog>
</template>

<style scoped lang="scss">
  @import 'UpdateCustomerService';
</style>
